local addon, ns = ...
local cfg = ns.cfg
local tags = CreateFrame("Frame") 

local utf8sub = function(string, i, dots)
	local bytes = string:len()
	if (bytes <= i) then
		return string
	else
		local len, pos = 0, 1
		while(pos <= bytes) do
			len = len + 1
			local c = string:byte(pos)
			if c > 240 then
				pos = pos + 4
			elseif c > 225 then
				pos = pos + 3
			elseif c > 192 then
				pos = pos + 2
			else
				pos = pos + 1
			end
			if (len == i) then break end
		end

		if (len == i and pos <= bytes) then
			return string:sub(1, pos - 1)..(dots and "..." or "")
		else
			return string
		end
	end
end

-----------------
-- custom tags --
-----------------
oUF.Tags["My_PerHP"] = function(unit)

	local curhp, maxhp = UnitHealth(unit), UnitHealthMax(unit);

	if ((maxhp > 0) and (curhp < maxhp)) then

		return math.floor((curhp / maxhp * 100 + 0.05) * 10)/10 .. '%'; -- by myno

	end

end;
oUF.TagEvents["My_PerHP"] = oUF.TagEvents.perhp;

oUF.Tags["afkdnd"] = function(unit)
	if unit then
		return UnitIsAFK(unit) and "|cffffffff<AFK>|r " or UnitIsDND(unit) and "|cffffffff<DND>|r "
	end
end
oUF.TagEvents["afkdnd"] = "PLAYER_FLAGS_CHANGED"

oUF.Tags["abbrevname"] = function(unit)
	local oldName = UnitName(unit)
	local newName = (string.len(oldName) > 14) and string.gsub(oldName, "%s?(.[\128-\191]*)%S+%s", "%1. ") or oldName
	
	if not UnitIsPlayer(unit) then
		return utf8sub(newName, 14, false)
	else
		return oldName
	end
end
oUF.TagEvents["abbrevname"] = "UNIT_NAME_UPDATE"

if (not oUF.Tags["shortname"]) then
	oUF.Tags["shortname"] = function(unit)
		local oldName = UnitName(unit)
		local newName = (string.len(oldName) > 6) and string.gsub(oldName, "%s?(.[\128-\191]*)%S+%s", "%1. ") or oldName
		return utf8sub(newName, 6, false)
	end
end
oUF.TagEvents["shortname"] = "UNIT_NAME_UPDATE"

oUF.Tags["veryshortname"] = function(unit)
		local name = UnitName(unit)
		return utf8sub(name, 3, false)
	end
oUF.TagEvents["veryshortname"] = "UNIT_NAME_UPDATE"

oUF.Tags["raidhpname"] = function(u)
local name = UnitName(u)
local c, m = UnitHealth(u), UnitHealthMax(u) 
if c == 0 then return "RIP" elseif(UnitIsGhost(u)) then return "GHO" elseif(not UnitIsConnected(u)) then return "OFF" elseif c < m then return oUF.Tags["missinghp"](u) else return utf8sub(name, 6, false) end end
oUF.TagEvents["raidhpname"] = "UNIT_HEALTH UNIT_MAXHEALTH UNIT_NAME_UPDATE"

oUF.Tags["druidPower"] = function(unit)
	local min, max = UnitPower(unit, 0), UnitPowerMax(unit, 0)
	return UnitPowerType(unit) ~= 0 and format('|cffff8000 %d|r', min)
end
oUF.TagEvents["druidPower"] = 'UNIT_MAXPOWER UNIT_POWER UPDATE_SHAPESHIFT_FORM'

ns.tags = tags